package com.googlecode.maven.plugin.appassembler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.xeustechnologies.jtar.TarEntry;
import org.xeustechnologies.jtar.TarOutputStream;

/**
 * TGZ (.tar.gz) archiver.
 */
public class TgzArchiver
        extends AbstractArchiver
    {
    /**
     * {@inheritDoc}
     */
    public void archive(File sourceDirectory, File targetFile,
            List<String> executableFiles)
            throws IOException
        {
        OutputStream ostrm = null;
        try
            {
            ostrm = new GZIPOutputStream(new FileOutputStream(targetFile));
            TarOutputStream tostrm = null;
            try
                {
                tostrm = new TarOutputStream(ostrm);
                for (File file : FileUtils.
                        listFiles(sourceDirectory, null, true))
                    {
                    if (file.isFile())
                        {
                        String path = getRelativePath(sourceDirectory, file);
                        TarEntry entry = new TarEntry(file, path);
                        entry.setUserName("user");
                        if ((executableFiles != null) && executableFiles.
                                contains(path))
                            {
                            entry.getHeader().mode = 0100755;
                            }
                        tostrm.putNextEntry(entry);
                        InputStream istrm = null;
                        try
                            {
                            istrm = new FileInputStream(file);
                            IOUtils.copy(istrm, tostrm);
                            }
                        finally
                            {
                            IOUtils.closeQuietly(istrm);
                            }
                        }
                    }
                }
            finally
                {
                IOUtils.closeQuietly(tostrm);
                }
            }
        finally
            {
            IOUtils.closeQuietly(ostrm);
            }
        }
    }
